// 速道 SKU 选择组件， 主要是js业务逻辑处理相关
Component({

  properties: {
    /* 数据结构定义如下：

      [
        {
          skuId: 1,               // skuId              (字段名随意，使用方自己处理)
          imageURL: '',           // 该sku对应的图片      (字段名随意，使用方自己处理)
          price: 39900,           // sku实际价格         (字段名随意，使用方自己处理)
          ... 其他扩展字段 ...                            (字段名随意，使用方自己处理)
          
          stock: 100,             // 库存               
          isDefaultSelected: true,// 该sku是否默认选中    [※使用方必须保证字段名一致]
          skuAttributeList: [     // sku属性列表选项      [※使用方必须保证字段名一致]
            {
              attributeName: '颜色',        // 属性名   [※使用方必须保证字段名一致]
              attributeValue: '红色',       // 属性值   [※使用方必须保证字段名一致]
              attributeIcon: '属性前icon'   // 属性值   [※使用方必须保证字段名一致]
            }, {
              attributeName: '尺码',
              attributeValue: 'M',
              attributeIcon: '属性前icon'
            },
            .....    // 等等...
          ]
        },
        ...
      ]
    */
    skuList: {
      type: Array,
      value: [],
      observer: 'onSkuListInit'
    },
  },

  data: {
    uiSectionList: []
  },

  methods: {
    onSkuListInit: function (newVal, oldVal) {
      if (newVal.length == oldVal.length && newVal.length == 0) {
        return;
      }
      /* 1、 获取UI展示风格的数据结构, 最终结构如下：
        [
          {
            uiSectionTitle: '颜色',
            uiItemList: [
              {
                uiItemTitle: '红色',
                uiItemIcon: '图片',
                uiItemEnabled: true,
                uiItemSelected: false,
              }, {
                uiItemTitle: '蓝色',
                uiItemIcon: '图片',
                uiItemEnabled: true,
                uiItemSelected: false,
              },
              ....
            ]
          }, {
            uiSectionTitle: '尺寸',
            uiItemList: [
              {
                uiItemTitle: '100',
                uiItemIcon: '图片',
                uiItemEnabled: true,
                uiItemSelected: false,
              }, {
                uiItemTitle: '120',
                uiItemIcon: '图片',
                uiItemEnabled: true,
                uiItemSelected: false,
              },
              ....
            ]
          },
          ....
        ]

      */
      let uiSectionList = this.assemblingData(newVal);
      
      // 2、 处理skuAttribute的禁用
      this.handleSkuAttributeState(uiSectionList);
    },

    // 拼装UI风格的sku数据
    assemblingData: function(skuList = []) {
      let skuAttributeTitleSet = new Set();
      let skuAttributeMap = new Map();

      let selectedSkuList = skuList.filter(item => item.isDefaultSelected);
      let selectedSkuItem = {};
      if (selectedSkuList.length > 0){
        selectedSkuItem = selectedSkuList[0];
      }

      for (let i = 0; i < skuList.length; i++) {
        let skuAttributeList = (skuList[i] || {}).skuAttributeList || [];
        for (let j = 0; j < skuAttributeList.length; j++) {
          let skuAttribute = skuAttributeList[j];
          skuAttributeTitleSet.add(skuAttribute.attributeName);
          
          let skuAttributeMapValueList = [];
          if (skuAttributeMap.has(skuAttribute.attributeName)){
            skuAttributeMapValueList = skuAttributeMap.get(skuAttribute.attributeName) || [];
            // 查找map中是否已经存在了该属性值
            let idx = skuAttributeMapValueList.findIndex(item => item.uiItemTitle == skuAttribute.attributeValue);
            
            if(idx < 0){ // 没有找到，添加属性
              skuAttributeMapValueList.push({
                uiItemTitle: skuAttribute.attributeValue,
                uiItemIcon: skuAttribute.attributeIcon,
                uiItemEnabled: true,
                uiItemSelected: false,
              });
            }
          } else {
            skuAttributeMapValueList.push({
              uiItemTitle: skuAttribute.attributeValue,
              uiItemIcon: skuAttribute.attributeIcon,
              uiItemEnabled: true,
              uiItemSelected: false,
            });
          }
          skuAttributeMap.set(skuAttribute.attributeName, skuAttributeMapValueList);
          
        }
      }

      let uiSectionList = [];

      let skuAttributeTitleList = Array.from(skuAttributeTitleSet) || [];
      for (let i = 0; i < skuAttributeTitleList.length; i++){
        let uiSection = {};

        let uiSectionTitle = skuAttributeTitleList[i];
        let uiItemList = Array.from(skuAttributeMap.get(uiSectionTitle) || []);

        uiSection.uiSectionTitle = uiSectionTitle;
        uiSection.uiItemList = uiItemList;
        uiSectionList.push(uiSection);
      }

      // 处理默认选中处理
      if (selectedSkuItem.isDefaultSelected === true 
        && selectedSkuItem.skuAttributeList 
        && selectedSkuItem.skuAttributeList.length > 0) {
        // 有默认选中的
        for (let i = 0; i < uiSectionList.length; i++) {
          let uiSection = uiSectionList[i];
          let uiItemList = uiSection.uiItemList || [];

          for (let j = 0; j < uiItemList.length; j++) {
            let uiItem = uiItemList[j];
            uiItem.uiItemSelected = selectedSkuItem.skuAttributeList.findIndex(item => item.attributeName == uiSection.uiSectionTitle && item.attributeValue == uiItem.uiItemTitle) >= 0;
          }
        }
      }

      return uiSectionList;
    },

    // 处理skuAttribute的禁用
    handleSkuAttributeState: function (uiSectionList = []) {
      // 当前选中的sku属性
      let currentSelectOptionList = [];
      for (let i = 0; i < uiSectionList.length; i++){
        let uiSection = uiSectionList[i];
        let uiSectionTitle = uiSection.uiSectionTitle;
        let uiItemList = uiSection.uiItemList;
        for(let j = 0; j < uiItemList.length; j++){
          let uiItem = uiItemList[j];
          if (!uiItem.uiItemSelected) {
            continue;
          }
          currentSelectOptionList.push({
            attributeName: uiSectionTitle,
            attributeValue: uiItem.uiItemTitle
          });
        }
      }

      // 获取可选的sku列表
      let canSelectableSkuList = this.data.skuList;
      canSelectableSkuList = canSelectableSkuList.filter(item => {
        let isInclude = true;
        let skuAttributeList = item.skuAttributeList || [];

        for (let i = 0; i < currentSelectOptionList.length; i++){
          let currentSelectOption = currentSelectOptionList[i];
          let idx = skuAttributeList.findIndex(item => item.attributeName == currentSelectOption.attributeName && item.attributeValue == currentSelectOption.attributeValue);
          if(idx < 0){ // 没有找到
            isInclude = false;
          }
        }
        return isInclude;
      });
      
      // console.log('可选sku:', canSelectableSkuList);

      let canSelectableSkuAttributeList = [];
      for (let i = 0; i < canSelectableSkuList.length; i++) {
        let canSelectableSku = canSelectableSkuList[i];
        
        for (let j = 0; j < (canSelectableSku.skuAttributeList || []).length; j++){
          let canSelectableSkuAttribute = (canSelectableSku.skuAttributeList || [])[j];
          canSelectableSkuAttributeList.push(canSelectableSkuAttribute);
        }
        
      }
      for (let i = 0; i < uiSectionList.length; i++){
        let uiSection = uiSectionList[i];
        for (let j = 0; j < uiSection.uiItemList.length; j++) {
          let uiItem = uiSection.uiItemList[j];
          uiItem.uiItemEnabled = canSelectableSkuAttributeList.findIndex(item => item.attributeName == uiSection.uiSectionTitle && item.attributeValue == uiItem.uiItemTitle) >= 0;
        }
      }

      if (currentSelectOptionList.length == 1){
        let currentSelectOption = currentSelectOptionList[0];
        for (let i = 0; i < uiSectionList.length; i++){
          let uiSection = uiSectionList[i];
          let uiItemList = uiSection.uiItemList;
          if (uiSection.uiSectionTitle != currentSelectOption.attributeName){
            continue;
          }
          uiItemList = uiItemList.map(item => {
            item.uiItemEnabled = true;
            return item;
          });
        }
      }

      let infoTips = undefined;
      for(let i = 0; i < uiSectionList.length; i++){
        let uiSection = uiSectionList[i];
        let uiSectionTitle = uiSection.uiSectionTitle;

        let idx = uiSection.uiItemList.findIndex(item => item.uiItemSelected);
        if(idx < 0){
          infoTips = `请选择${uiSectionTitle}`;
          break;
        }
      }
      if (infoTips){
        this.triggerEvent('infotips', { errorMsg: infoTips});
      }

      if (currentSelectOptionList.length == uiSectionList.length && canSelectableSkuList.length > 0) { // 每一行都有选中
        this.triggerEvent('selected', {
          skuItem: canSelectableSkuList[0]
        });
      }
      this.setData({
        uiSectionList: uiSectionList
      });
    },


    // sku 属性点击处理
    onSkuAttributeTap: function(e) {
      let row = e.currentTarget.dataset.row;
      let column = e.currentTarget.dataset.column;
      let uiSectionList = this.data.uiSectionList || [];
      let attributeItem = uiSectionList[row].uiItemList[column];

      if (!attributeItem.uiItemEnabled) { return; }

      let uiItemSelected = attributeItem.uiItemSelected;

      uiSectionList[row].uiItemList = uiSectionList[row].uiItemList.map(item => {
        item.uiItemSelected = false;
        return item;
      });

      uiSectionList[row].uiItemList[column].uiItemSelected = !uiItemSelected;
      
      this.handleSkuAttributeState(uiSectionList);
    }
  },


})
